<?php

namespace app\admin\controller;

use app\BaseController;
use think\App;
use think\facade\Db;

/**
 * @author xjw
 * @class:TaskProduct 定时任务=>产品操作
 * @method:product 拉取商品  45分钟执行
 * @method:deal_product 处理商品相关
 * @return  
 */


class Facebooktwo extends BaseController
{

    protected $model = null;
    protected $token = '';
    
    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->token = 'EAAZAGLelrcSkBOycpvACr7nHnTr1NP9M1UAUAZBw95cwHJRoFNRR0eZCxjALP7ISsSPGzIuZBu4CBOBve9FD8TR0R0ONQrwIDbVQwl6m9xehujZBGuhiZAf9iPndrcoSzFEDOIX2ZC65P4PZB9HBOQqTqXj14toqFwx62ATLHDNnzwaZAAZBkMgBlYZATWJ';
    }

    public function access_token()
    {
        $url = 'https://graph.facebook.com/v18.0/oauth/access_token?grant_type=fb_exchange_token&client_id=1766012863869225&client_secret=0b36ddafef946129b0fd92898549ea0b&fb_exchange_token='.$this->token;
        $result = $this->geturl($url);
        halt($result);
    }

    public function advertising()
    {
        $type = 0;
        $where = array();
        $advplat_id = $this->request->request('advplat_id');
        if (!empty($advplat_id)) {
            $where['id'] = $advplat_id;
        }
        $result = array();
        $advplat = Db::name('advplat')
            ->where($where)
            ->where('id',24)
            ->order('updatetime asc')
            ->find();
        if($advplat){
            $result = $this->advertising_info($advplat,$type);
            $updatetime['updatetime'] = time();
            Db::name('advplat')
                ->where('id',$advplat['id'])
                ->update($updatetime);
        }
        return success('操作成功',$result);
    }

    public function advertising_yesterday()
    {
        $type = 1;
        $where = array();
        $advplat_id = $this->request->request('advplat_id');
        if (!empty($advplat_id)) {
            $where['id'] = $advplat_id;
        }
        $result = array();
        $advplat = Db::name('advplat')
            ->where($where)
            ->where('id',24)
            ->order('updatetime_yesterday asc')
            ->find();
        if($advplat){
            $result = $this->advertising_info($advplat,$type);
            $updatetime_yesterday['updatetime_yesterday'] = time();
            Db::name('advplat')
                ->where('id',$advplat['id'])
                ->update($updatetime_yesterday);
        }
        return success('操作成功',$result);
    }

    public function advertising_info($advplat,$type){
        if($type == 1){//核实昨天的广告
            $date_start = date('Y-m-d', strtotime('-1 days'));
        }else{
            $date_start = date('Y-m-d', time());
        }
        $appsecret_proof= hash_hmac('sha256', $this->token, '0b36ddafef946129b0fd92898549ea0b');
        if(!empty($advplat['account'])){
            $account = explode(',', $advplat['account']);
        }else{
            $account = array();
        }
        $advertising_arr = array();
        $advertising_arr['cost'] = 0;
        if(!empty($account)){
            $arr_total = array();
            $success_num = 0;
            foreach ($account as $k=>$v) {
                if($type == 1){//核实昨天的广告
                    $url = 'https://graph.facebook.com/v18.0/act_'.$v.'/insights?access_token='.$this->token.'&debug=all&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&date_preset=yesterday&appsecret_proof='.$appsecret_proof;
                }else{
                    $url = 'https://graph.facebook.com/v18.0/act_'.$v.'/insights?access_token='.$this->token.'&debug=all&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&date_preset=today&appsecret_proof='.$appsecret_proof;
                }
                $result = $this->geturl($url);
                if (!empty($result)) {

                    $arr = array();
                    $arr['date_start'] = '';
                    $arr['date_stop'] = '';
                    $arr['impressions'] = '';
                    $arr['spend'] = 0;
                    $arr['error'] = '';

                    $result = json_decode($result,true);
                    if (!empty($result['data']) && isset($result['data'])) {
                        foreach ($result['data'] as $ka=>$va) {
                            $arr['advplat_id'] = $advplat['id'];
                            $arr['account_id'] = $va['account_id'];
                            $arr['date_start'] = $va['date_start'];
                            $date_start = $va['date_start'];
                            $arr['date_stop'] = $va['date_stop'];
                            $arr['impressions'] = $va['impressions'];
                            $arr['spend'] = $va['spend'];
                            $arr_total[] = $arr;
                            $success_num += 1;

                            $advertising_arr['cost'] += $va['spend'];
                            $advertising_arr['plat_account'] = $advplat['id'];
                            $advertising_arr['plat'] = $advplat['adv_id'];
                            $advertising_arr['admin_id'] = $advplat['admin_ids'];
                            $advertising_arr['create_time'] = date('Y-m-d 00:00:00',strtotime($va['date_start']));
                        }
                    }elseif(!empty($result['error']['message']) && isset($result['error']['message'])){
                        $arr['advplat_id'] = $advplat['id'];
                        $arr['account_id'] = $v;
                        $arr['date_start'] = $date_start;
                        $arr['error'] = $result['error']['message'];
                        $arr_total[] = $arr;
                    }elseif(empty($result['data'])){
                        $arr['advplat_id'] = $advplat['id'];
                        $arr['account_id'] = $v;
                        $arr['date_start'] = $date_start;
                        $arr_total[] = $arr;
                    }
                }
            }
        }
        //二次验证
        $test_api = table('advertisingapi')
                ->where('advplat_id', $advplat['id'])
                ->where('date_start',$date_start)
                ->find();
        if(!empty($test_api)){
            if(!empty($arr_total) && !empty($success_num)){
                table('advertisingapi')
                    ->where('advplat_id', $advplat['id'])
                    ->where('date_start',$date_start)
                    ->delete();
                table('advertisingapi')->insertAll($arr_total);
            }
        }else{
            table('advertisingapi')->insertAll($arr_total);
        }

        //录入到手动花费
        if(!empty($advertising_arr['cost'])){
            $advertising_arr['type'] = 1;
            table('advertising')
                ->where('plat_account', $advertising_arr['plat_account'])
                ->where('create_time',$advertising_arr['create_time'])
                ->where('type',1)
                ->delete();
            table('advertising')->insert($advertising_arr);
        }

        return $success_num;
    }

    function geturl($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

}
